﻿using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Media;

namespace LogoFX.Infra
{
	public static class VisualAndLogicalTreesHelpers
	{

		public static T GetVisualDescendent<T>(DependencyObject d) where T : DependencyObject
		{
			return GetVisualDescendents<T>(d).FirstOrDefault();
		}

		public static IEnumerable<T> GetVisualDescendents<T>(DependencyObject d) where T : DependencyObject
		{
			for (int n = 0; n < VisualTreeHelper.GetChildrenCount(d); n++)
			{
				DependencyObject child = VisualTreeHelper.GetChild(d, n);

				if (child is T)
				{
					yield return (T)child;
				}

				foreach (T match in GetVisualDescendents<T>(child))
				{
					yield return match;
				}
			}

			yield break;
		}

        public static T FindVisualAncestor<T>(this DependencyObject obj, bool includeThis) where T : DependencyObject
        {
            if (!includeThis)
                obj = VisualTreeHelper.GetParent(obj);

            while (obj != null && (!(obj is T)))
            {
                obj = VisualTreeHelper.GetParent(obj);
            }

            return obj as T;
        }
#if !SILVERLIGHT
        public static T FindLogicalAncestor<T>(this DependencyObject obj, bool includeThis) where T : DependencyObject
        {
            if (!includeThis)
                obj = LogicalTreeHelper.GetParent(obj);

            while (obj != null && (!(obj is T)))
            {
                obj = LogicalTreeHelper.GetParent(obj);
            }

            return obj as T;
        }
#endif
	}
}
